<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>灵珠修真记 - 事件数据查询</title>
    <link href="/api/assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="/api/assets/css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .container { margin-top: 30px; }
        .search-box { margin: 20px 0; }
        .table-responsive { margin-top: 20px; }
        .pagination { margin-top: 20px; }
        
        /* 顶部信息区域样式 */
        .top-info {
            transition: all 0.3s ease;
            overflow: hidden;
            max-height: 0;
            margin-bottom: 0;
        }
        
        /* 悬浮球样式 */
        .float-button {
            position: fixed;
            top: 30%;
            left: 20px;
            z-index: 1000;
            display: block;
            background-color: #0d6efd;
            color: white;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            cursor: move;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        }
        
        .float-button:hover {
            transform: scale(1.1);
            box-shadow: 0 3px 8px rgba(0,0,0,0.3);
        }
        
        .float-button.account-manage {
            top: 20%;
            background-color: #198754;
        }
        
        /* 展开/收起按钮 */
        .toggle-button {
            display: block;
            width: 100%;
            text-align: center;
            padding: 5px;
            background-color: #f8f9fa;
            border: none;
            border-radius: 0 0 8px 8px;
            color: #6c757d;
            cursor: pointer;
            margin-bottom: 20px;
        }
        
        .toggle-button:hover {
            background-color: #e9ecef;
        }
        
        /* 原有样式保持不变 */
        .instructions { 
            background-color: #f8f9fa; 
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #0d6efd;
        }
        .payment-info {
            background-color: #fff3cd;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #ffc107;
        }
        .payment-info h5 {
            color: #856404;
            margin-bottom: 15px;
        }
        .payment-info p {
            margin-bottom: 10px;
            color: #333;
        }
        .wechat-id {
            background-color: #e9ecef;
            padding: 5px 10px;
            border-radius: 4px;
            font-family: monospace;
            font-weight: bold;
        }
        .instructions h5 {
            color: #0d6efd;
            margin-bottom: 15px;
        }
        .instructions ol {
            padding-left: 20px;
            margin-bottom: 0;
        }
        .instructions li {
            margin-bottom: 10px;
            line-height: 1.6;
        }
        .important-note {
            color: #dc3545;
            font-weight: bold;
        }
        .important-note1 {
            color: #0a00ff;
            font-weight: bold;
        }
        .search-keywords {
            background-color: #e9ecef;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
        }
        .stats-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 30px;
        }
        .stats-card {
            width: 100%;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            background-color: #fff;
            transition: transform 0.2s;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .stats-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #0d6efd;
            margin: 10px 0;
        }
        .stats-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        .card-header {
            background-color: #f8f9fa;
            border-bottom: none;
            border-radius: 10px 10px 0 0 !important;
            padding: 12px;
        }
        .card-body {
            padding: 15px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 悬浮球 -->
        <div class="float-button" id="infoButton" title="显示说明">
            <i class="bi bi-info-circle-fill"></i>
        </div>
        
        <!-- 账号管理悬浮球 -->
        <div class="float-button account-manage" id="accountButton" style="display: block" title="多账号管理">
            <i class="bi bi-people-fill"></i>
        </div>
        
        <!-- 用户查询悬浮球 -->
        <div class="float-button user-search" id="userSearchButton" style="display: block; top: 40%; background-color: #dc3545;" title="获取广告">
            <i class="bi bi-search"></i>
        </div>
        
        <!-- 顶部信息区域 -->
        <div class="top-info">
            <h2 class="text-center mb-4">灵珠修真记 - 事件数据查询</h2>
            
            <!-- 结账说明 -->
            <div class="payment-info">
                <h5>💰 结账说明</h5>
                <p><strong>结账时间：</strong>次日上午结账</p>
                <p><strong>添加微信：</strong><span class="wechat-id">DXL666bbb</span></p>
                <p class="mb-0 text-muted">请务必在添加好友时备注您的快手昵称_nickId，以便及时处理结账事宜。</p>
            </div>
            
            <div class="instructions">
                <h5>📌 重要说明</h5>
                <ol>
                    <li>
                        <strong>查询步骤：</strong>
                        <ul>
                            <li>找官方微信：<span class="wechat-id">DXL666bbb</span>拿到二维码
                            </li>
                            <li class="important-note">快手扫码 提示扫码成功之后返回精选界面 一直上划视频 直到看到灵珠修真记广告</li>
                            <li class="important-note">进入游戏之后点击右上角头像进行登录 (不登录查不到数据)</li>
                            <li class="important-note">刚扫码结束进去游戏看到的广告都是无效的,等待15分钟以上,广告变成其他游戏</li>
                            <li class="important-note">如果不小心退出了，快手首页左上角点击三条横杠->小游戏中心->进入游戏</li>
                            <li class="important-note">看完广告后等待一分钟，回到本页面查询数据</li>
                        </ul>
<!--                        <ul>-->
<!--                            <li>在快手搜索以下关键词之一：-->
<!--                                <span class="search-keywords">灵珠修真记</span>、-->
<!--                                <span class="search-keywords">灵珠修仙</span>、-->
<!--                                <span class="search-keywords">灵珠修真</span>、-->
<!--                                <span class="search-keywords">修仙灵珠</span>-->
<!--                            </li>-->
<!--                            <li>看到广告后从广告点进入游戏</li>-->
<!--                            <li class="important-note">点击右上角头像进行登录 (不登录查不到数据)</li>-->
<!--                            <li>看完广告后等待一分钟，回到本页面查询数据</li>-->
<!--                        </ul>-->
                    </li>
                    <li class="important-note1">
                        ⚠️ 重要提示：如果一分钟后查询不到数据，可能原因：
                        <ul>
                            <li>账号被拉黑</li>
                            <li>绑定失败/游戏里面没登录</li>
                            <li>快手昵称与游戏中登录的昵称不一致</li>
                        </ul>
                    </li>
                </ol>
            </div>
        </div>
        
        <!-- 展开/收起按钮 -->
        <button class="toggle-button" onclick="toggleTopInfo()">
            <i class="bi bi-chevron-down"></i> 展开说明
        </button>

        <div class="row search-box">
            <div class="col-md-8 offset-md-2">
                <div class="input-group">
                    <input type="text" id="nickname" class="form-control" placeholder="快手昵称">
                    <input type="text" id="nickId" class="form-control" placeholder="NickID">
                    <button class="btn btn-primary" onclick="searchEvents(1)">搜索</button>
                </div>
                <div class="text-muted mt-2 small">
                    提示：可以输入昵称或ID进行搜索，支持单独使用或组合查询
                </div>
                <div class="alert alert-info mt-3" role="alert">
                    <h6 class="alert-heading mb-2"><i class="bi bi-info-circle"></i> ID查询功能说明</h6>
                    <p class="mb-1">• 此处的ID是小游戏内部的nickId 不是快手号的ID</p>
                    <p class="mb-0">• 2024年4月14号0点 灵珠修真记游戏停止获取数据 大家不用在玩了</p>
                </div>
            </div>
        </div>

        <!-- 统计信息卡片 -->
        <div id="statsContainer" style="display: none;">
            <div class="stats-container">
                <!-- 今日数据 -->
                <div class="stats-card">
                    <div class="card-header">
                        <h6 class="card-title mb-0">今日数据</h6>
                    </div>
                    <div class="card-body">
                        <div class="stats-value" id="todayValue">0.00</div>
                        <div class="stats-label">观看次数：<span id="todayCount">0</span></div>
                    </div>
                </div>
                
                <!-- 昨日数据 -->
                <div class="stats-card">
                    <div class="card-header">
                        <h6 class="card-title mb-0">昨日数据</h6>
                    </div>
                    <div class="card-body">
                        <div class="stats-value" id="yesterdayValue">0.00</div>
                        <div class="stats-label">观看次数：<span id="yesterdayCount">0</span></div>
                    </div>
                </div>
                
                <!-- 本周数据 -->
                <div class="stats-card">
                    <div class="card-header">
                        <h6 class="card-title mb-0">本周数据</h6>
                    </div>
                    <div class="card-body">
                        <div class="stats-value" id="weekValue">0.00</div>
                        <div class="stats-label">观看次数：<span id="weekCount">0</span></div>
                    </div>
                </div>
                
                <!-- 本月数据 -->
                <div class="stats-card">
                    <div class="card-header">
                        <h6 class="card-title mb-0">本月数据</h6>
                    </div>
                    <div class="card-body">
                        <div class="stats-value" id="monthValue">0.00</div>
                        <div class="stats-label">观看次数：<span id="monthCount">0</span></div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead class="table-dark">
                    <tr>
<!--                        <th>用户ID</th>-->
                        <th>昵称</th>
                        <th>价值</th>
                        <th>时间</th>
                    </tr>
                </thead>
                <tbody id="eventTableBody">
                </tbody>
            </table>
        </div>
        
        <nav>
            <ul class="pagination justify-content-center" id="pagination">
            </ul>
        </nav>
    </div>

    <script src="/api/assets/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        const pageSize = 10;
        
        // 添加展开/收起功能的JavaScript
        let isTopInfoVisible = false;
        
        // 初始化拖动功能
        function initDraggable() {
            console.log('Initializing draggable buttons');
            const infoButton = document.getElementById('infoButton');
            const accountButton = document.getElementById('accountButton');
            
            if (infoButton) {
                console.log('Info button found, making draggable');
                makeDraggable(infoButton);
            } else {
                console.log('Info button not found');
            }
            
            if (accountButton) {
                console.log('Account button found, making draggable');
                makeDraggable(accountButton);
            } else {
                console.log('Account button not found');
            }
        }
        
        // 让元素可拖动的函数
        function makeDraggable(element) {
            if (!element) return;
            
            let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            let isDragging = false;
            let dragStartTime = 0;
            let moved = false;
            
            console.log('Setting up draggable for', element.id);
            
            // 防止点击穿透
            element.addEventListener('click', function(e) {
                if (moved) {
                    e.preventDefault();
                    e.stopPropagation();
                    moved = false;
                }
            });
            
            element.onmousedown = function(e) {
                console.log('Mouse down on', element.id);
                e = e || window.event;
                e.preventDefault();
                
                // 记录点击开始时间
                dragStartTime = new Date().getTime();
                isDragging = false;
                moved = false;
                
                // 获取鼠标点击的初始位置
                pos3 = e.clientX;
                pos4 = e.clientY;
                
                document.onmouseup = function(e) {
                    console.log('Mouse up', element.id);
                    // 停止移动
                    document.onmouseup = null;
                    document.onmousemove = null;
                    
                    // 检查是否是点击事件（短时间内没有移动）
                    const clickDuration = new Date().getTime() - dragStartTime;
                    if (!moved && clickDuration < 300) {
                        console.log('Click detected on', element.id);
                        // 如果是说明按钮
                        if (element.id === 'infoButton') {
                            toggleTopInfo(true);
                        }
                        // 如果是账号管理按钮
                        else if (element.id === 'accountButton') {
                            window.location.href = '/api/login-register.html';
                        }
                    }
                };
                
                // 鼠标移动事件
                document.onmousemove = function(e) {
                    e = e || window.event;
                    e.preventDefault();
                    
                    // 标记为正在拖动
                    isDragging = true;
                    moved = true;
                    
                    // 计算新位置
                    pos1 = pos3 - e.clientX;
                    pos2 = pos4 - e.clientY;
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    
                    console.log('Moving', element.id, 'to', element.offsetTop - pos2, element.offsetLeft - pos1);
                    
                    // 设置元素的新位置
                    element.style.top = (element.offsetTop - pos2) + "px";
                    element.style.left = (element.offsetLeft - pos1) + "px";
                };
            };
            
            // 触摸事件
            element.ontouchstart = function(e) {
                console.log('Touch start on', element.id);
                
                dragStartTime = new Date().getTime();
                isDragging = false;
                moved = false;
                
                const touch = e.touches[0];
                pos3 = touch.clientX;
                pos4 = touch.clientY;
                
                e.preventDefault(); // 防止滚动
                
                document.ontouchend = function(e) {
                    console.log('Touch end', element.id);
                    document.ontouchend = null;
                    document.ontouchmove = null;
                    
                    // 检查是否是点击事件（短时间内没有移动）
                    const clickDuration = new Date().getTime() - dragStartTime;
                    if (!moved && clickDuration < 300) {
                        console.log('Touch click detected on', element.id);
                        // 如果是说明按钮
                        if (element.id === 'infoButton') {
                            toggleTopInfo(true);
                        }
                        // 如果是账号管理按钮
                        else if (element.id === 'accountButton') {
                            window.location.href = '/api/login-register.html';
                        }
                    }
                };
                
                document.ontouchmove = function(e) {
                    e.preventDefault();
                    
                    isDragging = true;
                    moved = true;
                    
                    const touch = e.touches[0];
                    pos1 = pos3 - touch.clientX;
                    pos2 = pos4 - touch.clientY;
                    pos3 = touch.clientX;
                    pos4 = touch.clientY;
                    
                    console.log('Touch moving', element.id, 'to', element.offsetTop - pos2, element.offsetLeft - pos1);
                    
                    element.style.top = (element.offsetTop - pos2) + "px";
                    element.style.left = (element.offsetLeft - pos1) + "px";
                };
            };
        }
        
        function toggleTopInfo(forceShow = false) {
            const topInfo = document.querySelector('.top-info');
            const toggleButton = document.querySelector('.toggle-button');
            const floatButton = document.querySelector('.float-button');
            
            if (forceShow) {
                isTopInfoVisible = false;
            }
            
            if (isTopInfoVisible) {
                // 收起
                topInfo.style.maxHeight = '0';
                topInfo.style.marginBottom = '0';
                toggleButton.innerHTML = '<i class="bi bi-chevron-down"></i> 展开说明';
                floatButton.style.display = 'block';
                
                // 滚动到搜索框
                document.querySelector('.search-box').scrollIntoView({ behavior: 'smooth' });
            } else {
                // 展开
                topInfo.style.maxHeight = topInfo.scrollHeight + 'px';
                topInfo.style.marginBottom = '20px';
                toggleButton.innerHTML = '<i class="bi bi-chevron-up"></i> 收起说明';
                floatButton.style.display = 'none';
                
                if (forceShow) {
                    // 滚动到顶部
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                }
            }
            
            isTopInfoVisible = !isTopInfoVisible;
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', function() {
            console.log('Window loaded');
            
            // 确保两个按钮都显示出来
            const infoButton = document.getElementById('infoButton');
            if (infoButton) {
                infoButton.style.display = 'block';
                console.log('Info button displayed');
            }
            
            const accountButton = document.getElementById('accountButton');
            if (accountButton) {
                accountButton.style.display = 'block';
                console.log('Account button displayed');
            }
            
            // 稍微延迟初始化拖动功能，确保DOM完全加载
            setTimeout(function() {
                initDraggable();
            }, 500);
        });
        
        function searchEvents(page) {
            const nickname = document.getElementById('nickname').value.trim();
            const nickId = document.getElementById('nickId').value.trim();
            
            if (!nickname && !nickId) {
                alert('请输入快手昵称或ID');
                return;
            }
            
            currentPage = page;
            
            // 在搜索开始时显示统计信息
            document.getElementById('statsContainer').style.display = 'grid';
            
            // 清空表格内容
            const tbody = document.getElementById('eventTableBody');
            tbody.innerHTML = '<tr><td colspan="3" class="text-center">搜索中...</td></tr>';
            
            // 清空分页
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            // 构建查询参数
            const params = new URLSearchParams();
            if (nickname) params.append('nickname', nickname);
            if (nickId) params.append('nickId', nickId);
            params.append('page', page);
            params.append('size', pageSize);
            
            fetch(`/api/cost/search?${params.toString()}`)
                .then(response => response.json())
                .then(response => {
                    console.log('Response:', response);
                    
                    // 检查响应状态
                    if (response.code !== 200) {
                        throw new Error(response.msg || '查询失败');
                    }
                    
                    const data = response.data;
                    console.log('Data:', data);
                    
                    if (!data || data.total === 0) {
                        // 清空表格显示无数据信息
                        tbody.innerHTML = '<tr><td colspan="3" class="text-center">暂无数据</td></tr>';
                        // 清空统计数据
                        clearStats();
                        // 清空分页
                        pagination.innerHTML = '';
                        let message = '未找到数据，请确认：\n';
                        if (nickname) message += '1. 昵称输入是否正确\n';
                        if (nickId) message += '2. ID输入是否正确\n';
                        message += '3. 是否已在游戏中完成登录\n4. 是否等待了1分钟';
                        alert(message);
                    } else {
                        // 显示统计信息
                        updateStats(data.stats);
                        displayEvents(data);
                        updatePagination(data);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    // 发生错误时也清空数据
                    tbody.innerHTML = '<tr><td colspan="3" class="text-center">查询出错</td></tr>';
                    clearStats();
                    pagination.innerHTML = '';
                    alert('查询出错，请稍后重试\n' + error.message);
                });
        }
        
        function displayEvents(data) {
            console.log('Displaying events:', data);
            const tbody = document.getElementById('eventTableBody');
            tbody.innerHTML = '';
            
            if (!data.records || data.records.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="3" class="text-center">暂无数据</td>';
                tbody.appendChild(row);
                return;
            }
            
            data.records.forEach(record => {
                console.log('Processing record:', record);
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${record.nickname || '-'}</td>
                    <td>¥${record.userCost?.toFixed(2) || '0.00'}</td>
                    <td>${record.createTime || '-'}</td>
                `;
                tbody.appendChild(row);
            });
        }
        
        function updateStats(stats) {
            console.log('Updating stats:', stats);
            if (!stats) {
                console.warn('No stats data available');
                return;
            }
            
            document.getElementById('statsContainer').style.display = 'grid';
            
            // 更新统计数据
            const updateStatValue = (elementId, value, isCount = false) => {
                const element = document.getElementById(elementId);
                if (element) {
                    if (isCount) {
                        element.textContent = value || '0';
                    } else {
                        const numValue = parseFloat(value);
                        element.textContent = isNaN(numValue) ? '0.00' : numValue.toFixed(2);
                    }
                }
            };
            
            // 更新今日数据
            updateStatValue('todayCount', stats.today?.count, true);
            updateStatValue('todayValue', stats.today?.total_cost);
            
            // 更新昨日数据
            updateStatValue('yesterdayCount', stats.yesterday?.count, true);
            updateStatValue('yesterdayValue', stats.yesterday?.total_cost);
            
            // 更新本周数据
            updateStatValue('weekCount', stats.week?.count, true);
            updateStatValue('weekValue', stats.week?.total_cost);
            
            // 更新本月数据
            updateStatValue('monthCount', stats.month?.count, true);
            updateStatValue('monthValue', stats.month?.total_cost);
        }
        
        function updatePagination(data) {
            console.log('Updating pagination:', data);
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            if (!data || data.total === 0) return;
            
            const totalPages = data.pages || Math.ceil(data.total / pageSize);
            const currentPage = data.current || 1;
            
            // 上一页
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            prevLi.innerHTML = `
                <a class="page-link" href="#" onclick="event.preventDefault(); ${currentPage > 1 ? `searchEvents(${currentPage - 1})` : ''}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            `;
            pagination.appendChild(prevLi);
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                li.innerHTML = `
                    <a class="page-link" href="#" onclick="event.preventDefault(); searchEvents(${i})">${i}</a>
                `;
                pagination.appendChild(li);
            }
            
            // 下一页
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
            nextLi.innerHTML = `
                <a class="page-link" href="#" onclick="event.preventDefault(); ${currentPage < totalPages ? `searchEvents(${currentPage + 1})` : ''}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            `;
            pagination.appendChild(nextLi);
        }
        
        // 添加清空统计数据的函数
        function clearStats() {
            document.getElementById('statsContainer').style.display = 'none';
            // 清空所有统计值
            ['today', 'yesterday', 'week', 'month'].forEach(period => {
                document.getElementById(`${period}Count`).textContent = '0';
                document.getElementById(`${period}Value`).textContent = '0.00';
            });
        }

        // 添加用户查询按钮点击事件
        document.getElementById('userSearchButton').addEventListener('click', function() {
            window.location.href = '/api/user-search.html';
        });
    </script>
</body>
</html> 